import json
from functools import reduce

import pandas
from elasticsearch import Elasticsearch
from flask import Blueprint, request

from Utils.APIResponse import APIResponse
from Utils.TokenUtil import token_required
from View.search import _process_search_results, _construct_query, _get_search_params
from conf import es_url, student_csv, code_time_csv

data_blue = Blueprint("data", __name__)
es_client = Elasticsearch(hosts=es_url)


@data_blue.route('/data', methods=['POST'])
@token_required
def search(request_user_id):
    print(request_user_id)
    try:
        # Get parameters from the frontend
        search_params = _get_search_params(request)

        # Construct the query
        query = _construct_query(search_params)

        # Execute the search request
        response = es_client.search(index="conversation", body=query)

        # Extract and process search results
        search_results = _process_search_results(search_params, response)

        total_results = search_results["total_results"]
        df_code = pandas.read_csv(code_time_csv)
        teacher_num = len(df_code['code'].tolist())
        total_hours = reduce(lambda x, y: x + y, df_code['time'].tolist())
        df_student = pandas.read_csv(student_csv)
        student_num = len(df_student['code'].tolist())

        return APIResponse.success(data={
            "total_results": total_results,
            "total_hours": total_hours,
            "teacher_num": teacher_num,
            "student_num": student_num
        })

    except (json.JSONDecodeError, ValueError) as e:
        return APIResponse.error({'error': 'Invalid JSON format: ' + str(e)}, status_code=400)

    except Exception as e:
        return APIResponse.error({'error': 'Error searching: ' + str(e)}, status_code=500)
